﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace ALS.Component.Tools.Helpers
{
    public class SerializeHelper
    {
        public static T Deserialize<T>(string xml)
        {
            var serializer = new XmlSerializer(typeof(T));
            var t = default(T);
            using (var stringReader = new StringReader(xml))
            {
                t = (T)serializer.Deserialize(stringReader);
                stringReader.Close();
                stringReader.Dispose();
            }
            return t;
        }

        public static dynamic Deserialize(Type type, string xml)
        {
            var serializer = new XmlSerializer(type);
            dynamic t = null;
            using (var stringReader = new StringReader(xml))
            {
                t = serializer.Deserialize(stringReader);
                stringReader.Close();
                stringReader.Dispose();
            }
            return t;
        }

        public static string Serialize<T>(object obj)
        {
            var xml = string.Empty;
            using (var memoryStream = new MemoryStream())
            {
                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(memoryStream, obj);
                memoryStream.Seek(0, SeekOrigin.Begin);
                using (var streamReader = new StreamReader(memoryStream))
                {
                    xml = streamReader.ReadToEnd();
                    streamReader.Close();
                    streamReader.Dispose();
                }
                memoryStream.Close();
                memoryStream.Dispose();
            }
            return xml;
        }
    }
}
